<?php
/**
 * communit.as
 * @copyright (C)2008 J. William McCarthy, All Rights Reserved.
 * @category communitas
 * @package communitas
 * @author J. William McCarthy
 * @link http://communit.as communit.as
 * @license http://communit.as/docs/license License
 */

/**
 *
 * @package communitas
 * @subpackage cms_controllers
 * @license http://communit.as/docs/license License 
 */

class Cms_IndexController extends App_Controller_Action_Abstract {

	function init(){			
		parent::init();
	}

	function indexAction(){
		$pages_table = new Cms_Pages();
		$posts = $pages_table->fetchAll("type = 'post'", 'posted_on desc');
		$tmp_posts = array();
		if(count($posts) > 0){
			foreach($posts as $post){
				$post = $post->toArray();
				$post['text'] = App_Common::makeParagraphs($post['text']);
				$tmp_posts[] = $post;
			}
			$this->view->posts = $tmp_posts;
		}
	}

	function detailAction(){
		$request = new App_Request($this->getRequest());
		$pages_table = new Cms_Pages();
		if($request->has('id')){
			$post = $pages_table->fetchRow('id = ' . $request->id);
			if(!is_null($post)){
				$post = $post->toArray();
				$post['text'] = App_Common::makeParagraphs($post['text']);
				$this->view->post = $post;				
			} else {
				$this->_redirect('/auth/missing');
			}
		} else {
			$this->_redirect('/auth/missing');
		}
	}

	function rssAction(){
		$pages_table = new Cms_Pages();
		$posts = $pages_table->fetchAll("type = 'post'", 'posted_on desc', 20);
		$tmp_posts = array();	
		if(count($posts) > 0){
			foreach($posts as $post){
				$post = $post->toArray();
				$post['text'] = App_Common::makeParagraphs($post['text']);
				$post['permalink'] = '/blog/' . $post['id'] . '/' . App_Common::makeSeoFriendly($post['title']);
				$tmp_posts[] = $post;
			}
			$this->view->posts = $tmp_posts;
		}
		header('Content-Type: application/rss+xml');
	}

	function pageAction(){
		$pages_table = new Cms_Pages();
		$slug = $this->_request->getParam('slug');
		$where = $pages_table->getAdapter()->quoteInto('slug = ?', $slug);		
		$page = $pages_table->fetchRow($where);
		if(!is_null($page)){
			$page = $page->toArray();
			$page['text'] = App_Common::makeParagraphs($page['text']);
			$this->view->page = $page; 
			$this->view->pagetitle = $page['title'];
		} else {
			$this->_redirect('/auth/missing');
		}
	}

	function syncAction(){
		$pages_table = new Cms_Pages();
		$pages_table->syncPages();
		$pages_table->syncPosts();		
		$out = Zend_Json::encode(array('complete' => true));
		die($out);
	}

	function deleteAction(){
		$pages_table = new Cms_Pages();
		$id = $this->_request->getParam('id', null);
		if(!is_null($id)){
			$pages_table->delete('id = '.$id);
		}
		die('post deleted');
	}

}
